<template>
  <el-form style="max-width: 700px" :model="baseInfo" :rules="!isFormDisabled?rules:''" label-width="auto"
    class="demo-ruleForm" :size="formSize" status-icon ref="formRef">
    <el-form-item label="药房名称:" prop="name">
      <el-input v-model="baseInfo.name" maxlength="50" placeholder="请输入药品名称" show-word-limit type="text" clearable
        v-if="!isFormDisabled" />
      <el-text v-else class="mx-1">{{baseInfo.name}}</el-text>
    </el-form-item>

    <el-form-item label="药库名称:" prop="storage_name">
      <el-input v-model="baseInfo.storage_name" maxlength="50" placeholder="请输入药库名称" show-word-limit type="text"
        clearable v-if="!isFormDisabled" />
      <el-text v-else class="mx-1">{{baseInfo.storage_name}}</el-text>
    </el-form-item>

    <el-form-item label="联系人:">
      <el-input v-model="baseInfo.user_name" maxlength="50" placeholder="请输入药房联系人" show-word-limit type="text" clearable
        v-if="!isFormDisabled" />
      <el-text v-else class="mx-1">{{baseInfo.user_name?baseInfo.user_name:'无'}}</el-text>
    </el-form-item>

    <el-form-item label="手机号:" prop="user_mobile">
      <el-input v-model="baseInfo.user_mobile" maxlength="11" placeholder="请输入药房联系人电话" show-word-limit type="text"
        clearable v-if="!isFormDisabled" />
      <el-text v-else class="mx-1">{{baseInfo.user_mobile}}</el-text>
    </el-form-item>
    <el-form-item label="调剂系统:" prop="system">
      <el-radio-group v-model="baseInfo.system" v-if="!isFormDisabled">
        <el-radio :value="1">骁柔大健康</el-radio>
        <el-radio :value="2">第三方系统 <el-select v-if="baseInfo.system == 2" v-model="baseInfo.drugstore_supplier_id"
            style="margin-left: 6px;width:192px" placeholder="请选择药品供应商" value-key="id">
            <el-option v-for="item in supplier" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-radio>
      </el-radio-group>
      <el-text v-else class="mx-1">{{baseInfo.system == 1 ?'骁柔大健康':baseInfo.drugstore_supplier_name}}</el-text>
    </el-form-item>


    <el-form-item label="处方推送模式:" prop="prescription_push_type">
      <el-radio-group v-model="baseInfo.prescription_push_type" v-if="!isFormDisabled">
        <el-radio :value="1">自动</el-radio>
        <el-radio :value="2">手动</el-radio>
      </el-radio-group>
      <el-text v-else class="mx-1">{{baseInfo.prescription_push_type == 1 ?'自动' : '手动'}}</el-text>
    </el-form-item>

    <el-form-item label="药房地址">
      <el-cascader v-model="selectedOptions" :options="address"
        :props="{ value: 'id', label: 'title', children: 'child' }" @change="handleChange" style="flex:1" clearable
        v-if="!isFormDisabled" />
      <el-text v-else class="mx-1">{{baseInfo.provincesName ? baseInfo.provincesName :'无'}}</el-text>
    </el-form-item>

    <el-form-item label="药房详细地址:">
      <el-input v-model="baseInfo.address" maxlength="200" placeholder="请输入药房地址" show-word-limit type="textarea"
        clearable v-if="!isFormDisabled" />
      <el-text v-else class="mx-1">{{baseInfo.address ?baseInfo.address:'无'}}</el-text>
    </el-form-item>

    <el-form-item label="药房坐标:" prop="coordinate">
      <el-input v-model="coordinate" style="width:300px" maxlength="100" placeholder="请输入药房坐标以逗号分割" show-word-limit
        type="text" @change="getCoordinate" clearable v-if="!isFormDisabled" />
      <el-text v-else-if="isFormDisabled&&baseInfo.long&&baseInfo.lat"
        class="mx-1">{{baseInfo.long + ',' + baseInfo.lat}}</el-text>
      <el-text v-else-if="isFormDisabled&&!baseInfo.long&&!baseInfo.lat" class="mx-1">无</el-text>
    </el-form-item>

    <el-form-item label="药房状态:">
      <el-radio-group v-model="baseInfo.status" v-if="!isFormDisabled">
        <el-radio :value="1">正常</el-radio>
        <el-radio :value="2">下架</el-radio>
        <el-radio :value="3">关闭</el-radio>
      </el-radio-group>
      <el-text v-else class="mx-1">{{baseInfo.status === 1 ? '正常' : (baseInfo.status === 2 ? '下架' : '关闭')}}</el-text>
    </el-form-item>

    <el-form-item label="定时关闭:">
      <el-date-picker v-model="closeTime" type="datetimerange" start-placeholder="请选择开始时间" end-placeholder="请选择结束日期"
        format="YYYY-MM-DD HH:mm:00" date-format="YYYY/MM/DD ddd" value-format="YYYY-MM-DD HH:mm:ss" clearable
        time-format="A hh:mm:00" @change="getCloseTime" class="custom-date-picker" v-if="!isFormDisabled" />
      <el-text v-else-if="isFormDisabled&&baseInfo.close_start_time&&baseInfo.close_end_time"
        class="mx-1">{{baseInfo.close_start_time}} - {{baseInfo.close_end_time}}</el-text>
      <el-text v-else-if="isFormDisabled&&!baseInfo.close_start_time&&!baseInfo.close_end_time" class="mx-1">无</el-text>
    </el-form-item>

    <el-form-item label="关闭提示语:">
      <el-input v-model="baseInfo.close_tips" maxlength="40" placeholder="请输入关闭提示语" show-word-limit type="text"
        clearable v-if="!isFormDisabled" />
      <el-text v-else class="mx-1">{{baseInfo.close_tips?baseInfo.close_tips:'无'}}</el-text>
    </el-form-item>

    <el-form-item label="对公账户名称:" prop="account_name">
      <el-input v-model="baseInfo.account_name" maxlength="200" placeholder="请输入对公账号名称" show-word-limit type="text"
        clearable v-if="!isFormDisabled" />
      <el-text v-else class="mx-1">{{baseInfo.account_name}}</el-text>
    </el-form-item>

    <el-form-item label="开户行:" prop="bank_name">
      <el-input v-model="baseInfo.bank_name" maxlength="200" placeholder="请输入开户行" show-word-limit type="text" clearable
        v-if="!isFormDisabled" />
      <el-text v-else class="mx-1">{{baseInfo.bank_name}}</el-text>
    </el-form-item>

    <el-form-item label="开户行账号:" prop="card_num">
      <el-input v-model="baseInfo.card_num" maxlength="19" placeholder="请输入开户行账号" show-word-limit type="text" clearable
        v-if="!isFormDisabled" />
      <el-text v-else class="mx-1">{{baseInfo.card_num}}</el-text>
    </el-form-item>

    <el-form-item label="药房截单时间:">
      <el-time-picker v-model="baseInfo.statement_time" value-format="HH:mm" format="HH:mm" placeholder="请选择截单时间"
        clearable :default-value="statement_time" v-if="!isFormDisabled" />
      <el-text v-else class="mx-1">{{baseInfo.statement_time ? baseInfo.statement_time :'无' }}</el-text>
    </el-form-item>

    <el-form-item label="药房支持快递:">
      <el-select v-model="baseInfo.express" placeholder="请选择药房支持快递" value-key="express_id" v-if="!isFormDisabled">
        <el-option v-for="item in express" :key="item.express_id" :label="item.express_name" :value="item" />
      </el-select>
      <el-text v-else class="mx-1">{{baseInfo.express.express_name?baseInfo.express.express_name:'无'}}</el-text>
    </el-form-item>

  </el-form>
</template>

<script setup>
  import {
    addressList,
    expressList,
    supplierList,
    detailShow
  } from '/src/api/pharmacy/basis'
  import {
    reactive,
    ref,
    onMounted,
    nextTick,
    defineExpose
  } from 'vue'

  const props = defineProps({
    editId: String,
    isFormDisabled: Boolean
  });
  //重新定义
  const closeTime = ref('')
  const coordinate = ref('')
  const statement_time = ref(new Date())
  const selectedOptions = ref([]);
  const address = ref([]);
  const express = ref([])
  const supplier = ref([])
  const supplierId = ref('')
  const baseInfo = reactive({
    "name": "",
    "storage_name": "",
    "full_name": "",
    "province_id": "",
    "city_id": "",
    "district_id": "",
    "address": "",
    "user_name": "",
    "user_mobile": "",
    "system": 1,
    "drugstore_supplier_id": "",
    "close_tips": "",
    "close_end_time": "",
    "close_start_time": "",
    "lat": "",
    "long": "",
    "express": [],
    "express_type": "",
    "free_price": "",
    "no_free_price": "",
    "status": 1,
    "prescription_push_type": null,
    "property": "1"
  })
  const submitForm1 = ref({})
  const formRef = ref(null);

  const handleChange = (value) => {
    console.log('Selected value:', value);
    baseInfo.province_id = value[0]
    baseInfo.city_id = value[1] ? value[1] : '0'
    baseInfo.district_id = value[2] ? value[2] : '0'
  };
  //详情
  const getDetail = async () => {
    const result = await detailShow({
      id: props.editId
    });
    if (result.code === 200) {
      Object.assign(baseInfo, result.data.baseInfo);
      if (result.data.baseInfo.lat && result.data.baseInfo.long) {
        coordinate.value = result.data.baseInfo.lat + ',' + result.data.baseInfo.long
      }
      if (result.data.baseInfo.province_id && result.data.baseInfo.city_id && !result.data.baseInfo.district_id) {
        selectedOptions.value = [result.data.baseInfo.province_id, result.data.baseInfo.city_id]
      } else if (result.data.baseInfo.province_id && result.data.baseInfo.city_id && result.data.baseInfo
        .district_id) {
        selectedOptions.value = [result.data.baseInfo.province_id, result.data.baseInfo.city_id, result.data
          .baseInfo.district_id
        ]
      } else if (result.data.baseInfo.province_id && !result.data.baseInfo.city_id && !result.data.baseInfo
        .district_id) {
        selectedOptions.value = [result.data.baseInfo.province_id]
      }

      if (result.data.baseInfo.close_start_time && result.data.baseInfo.close_end_time) {
        closeTime.value = [result.data.baseInfo.close_start_time, result.data.baseInfo.close_end_time]
      }
      if (baseInfo.express.length > 0) {
        baseInfo.express = {
          ...baseInfo.express[0]
        }
      }

      console.log('详情', baseInfo);
    }
  };

  //地址
  const getAddress = async () => {
    const result = await addressList();
    address.value = result.data
  }
  //物流列表
  const getLogistics = async (id) => {
    const result = await expressList();
    const newArray = result.data.map(obj => {
      return {
        express_id: obj.id,
        express_name: obj.name
      };
    });
    express.value = newArray

  }

  const getSupplierList = async () => {
    const result = await supplierList();
    supplier.value = result.data
    console.log(result.data)
  }

  ///判断经纬度是否正确
  const isValidCoordinates = (value) => {
    // 匹配经度和纬度的正则表达式，范围为 -90 到 90，-180 到 180
    const regex = /^-?\d+(\.\d+)?(,|，)\s*-?\d+(\.\d+)?$/;
    return regex.test(value);
  };

  //经纬度验证规则
  const isValidCoordinatesR = (rule, value, callback) => {
    if (!isValidCoordinates(coordinate.value) && coordinate.value) {
      if (coordinate.value) {
        callback(new Error('请输入正确经纬度'))
      }
    } else {
      console.log('正确')
      callback()
    }
  }

  //调剂系统的验证
  const isSystem = (rule, value, callback) => {
    if (baseInfo.system == 2) {
      if (baseInfo.drugstore_supplier_id == '') {
        callback(new Error('请选择药品供应商'))
      } else {
        callback()
      }
    } else {
      console.log('正确')
      callback()
    }
  }

  //验证集合
  const rules = reactive({
    ['name']: [{
      required: true,
      message: "药房名称必填",
      trigger: 'submit'
    }],
    ['storage_name']: [{
      required: true,
      message: "药库名称必填",
      trigger: 'submit'
    }],
    ['user_mobile']: [{
      required: true,
      message: "手机号必填",
      pattern: /^1[345789]\d{9}$/,
      trigger: 'submit'
    }],
    ['system']: [{
      required: true,
      message: "请选择调剂系统",
      validator: isSystem,
      trigger: 'submit'
    }],
    ['prescription_push_type']: [{
      required: true,
      message: "请选择处方推送模式",
      trigger: 'submit'
    }],
    ['coordinate']: [{
      required: false,
      validator: isValidCoordinatesR,
      trigger: 'submit'
    }],
    ['account_name']: [{
      required: true,
      message: "请输入对公账户名称",
      trigger: 'submit'
    }],
    ['bank_name']: [{
      required: true,
      message: "请输入开户行",
      trigger: 'submit'
    }],
    ['card_num']: [{
      required: true,
      message: "收款账户不能为空",
      trigger: 'submit'
    }]
  });
  //重新定位

  onMounted(() => {
    nextTick(() => {
      getAddress()
      getSupplierList()
      if (props.editId) {
        getDetail()
        getLogistics(props.editId)
      } else {
        getLogistics()
      }
    })
  })

  const formSize = ref('default')

  const getCloseTime = (value) => {
    baseInfo.close_start_time = value[0] ? value[0] : ''
    baseInfo.close_end_time = value[1] ? value[1] : ''
    console.log(baseInfo)
  }

  const submitForm = async () => {
    try {
      const valid = await new Promise(resolve => {
        formRef.value.validate((valid, fields) => {
          resolve(valid);
        });
      });

      if (valid) {
        // 验证通过，执行提交逻辑
        console.log('submit!');
        console.log('submit!')
        const submit = {
          ...baseInfo,
          express: [{
            express_id: baseInfo.express.express_id,
            express_name: baseInfo.express.express_name
          }]
        }
        if (coordinate.value) {
          const coordinates = coordinate.value;
          const replacedCoordinates = coordinates.replace(/[,，]/g, ',');
          const formattedCoordinatesArray = replacedCoordinates.split(',');
          console.log(formattedCoordinatesArray);
          submit.long = formattedCoordinatesArray[0] ? formattedCoordinatesArray[0] : ''
          submit.lat = formattedCoordinatesArray[1] ? formattedCoordinatesArray[1] : ''
        }
        submitForm1.value = submit
        console.log('formEl', submit)
        // 其他提交逻辑...
      } else {
        // 验证不通过，输出错误信息
        console.log('error submit!');
      }
    } catch (error) {
      // 处理错误
      console.error('出现错误：', error);
    }
  };
  const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
  }
  defineExpose({
    async submitFormWithResult() {
      await submitForm(); // 假设这是你的 submitForm 方法
      return submitForm1.value; // 返回子组件的结果
    }
  }); // 暴露方法给父组件
</script>
<style lang="scss" scoped>
  .demo-ruleForm {
    padding: 20px 40px;
  }

  ::v-deep .el-form-item {
    margin-bottom: 20px;
  }

  ::v-deep .el-radio {
    font-weight: 400 !important;
  }

  /* 修改提示语颜色 */
  ::v-deep .el-range-input::placeholder {
    color: #b6bcc4;
    font-size: 12px;
  }

  .smTip {
    color: #e02020;
    font-size: 12px;
    margin-left: 12px;
  }
</style>